import WorkerBase
import MSData
import MSLogger

import datetime
import time
import urllib
import pdb

class Worker(WorkerBase.WorkerBase):
    def __init__(self, MSAPIUrl='http://api.car-online.ru'):
        self.MSUrl = MSAPIUrl


    def readURLData(self, Request, SKey, TimeRange):
        url = self.MSUrl + '/do?data=%s&skey=%s&begin=%s&end=%s' % (Request,
                                                                             SKey,
                                                                             TimeRange[0],
                                                                             TimeRange[1])
	#MSLogger.logDebug('url: %s' % (url))
        try:
            MSLogger.logDebug('Processing (%s-%s) of %s' % (TimeRange[0], TimeRange[1], SKey))
            MSLogger.logDebug('at %s' % (url))
            f = urllib.urlopen(url)
            d = f.readlines()
            if len(d) == 0:
                return None
            return d
        except Exception, err:
            MSLogger.logError('Worker::readURLData: failed with: %s' % (str(err)))

    def finalyzeObject(self, MSObject):
        if MSObject.canClearPGSMEvents:
            MSObject.canClearPGSMEvents = False
            MSObject.eventsPGSM = []
        if MSObject.canClearContactIdEvents:
            MSObject.canClearContactIdEvents = False
            MSObject.eventsContactId = []
        if MSObject.canClearBolidEvents:
            MSObject.canClearBolidEvents = False
            MSObject.eventsBolid = []

    def parseEvent(self, EventString):
        s = EventString.split('/>')[0]
        s = s.split('<')[1]
        s = s.split(' ')
        e = {}
        for prop in s[1:len(s)]:
            prop = prop.split('=')
            e[prop[0]] = prop[1].replace('"', '')
        return e
        
    def getEventsPGSM(self, MSObject):
        timeRange   = self.getBeginEnd(MSObject.lastEvent_PGSM)
        events      = self.readURLData('events', MSObject.objectSKey, timeRange)
        #MSObject.lastEvent_PGSM = datetime.datetime.strptime(timeRange[1], MSData.TIME_FORMAT_MAGIC)
        return events

    def processEventsPGSM(self, MSObject, Events):
        doneNum = 0
        #clearOffline = False
        if Events:
            for s in Events:
                try:
                    MSObject.clearOffline = True
                    e = MSData.MSEvent()
                    result = e.fromPGSM_API(self.parseEvent(s))
                    e.objectId = MSObject.objectPCNId
                    if MSObject.lastEvent_PGSM and MSObject.lastEvent_PGSM < e.eventGenerateTime:
                        MSObject.lastEvent_PGSM = e.eventGenerateTime
                    if not MSObject.lastEvent_PGSM:
                        MSObject.lastEvent_PGSM = e.eventGenerateTime
                    if result == True: MSObject.eventsPGSM.append(e)
                    #MSObject.lastEvent_PGSM = e.eventGenerateTime
                    doneNum += 1
                except Exception, err:
                    MSLogger.logDebug('Worker::processEventsPGSM: event(%s) error(%s)' % (str(s), str(err)))
                    continue

        #pdb.set_trace()
        if not MSObject.enableOfflineCritical:
            return doneNum
        #pdb.set_trace()
        if (not MSObject.cameOOS) and MSObject.lastEvent_PGSM and ((datetime.datetime.fromtimestamp(time.time()) - MSObject.lastEvent_PGSM) > datetime.timedelta(0, 600)):
            e = MSData.MSEvent()
            MSLogger.logInfo('Channel OFF: oss(%s) le(%s:%s)' % (str(MSObject.cameOOS), str(MSObject.lastEvent_PGSM),str(datetime.datetime.fromtimestamp(time.time()))))
            e.hasStatic = True
            e.contactIdFull = 'auto'
            e.contactIdType = '3551'
            e.contactIdGroup = '00'
            e.contactIdZona = '00'
            e.objectId = MSObject.objectPCNId
            MSObject.eventsPGSM.append(e)
            MSObject.cameOOS = True
            #MSObject.lastEvent_PGSM = None
            MSObject.clearOffline = False
            doneNum += 1
            return doneNum
        if MSObject.cameOOS and MSObject.clearOffline:
            e = MSData.MSEvent()
            MSLogger.logInfo('DBG 2')
            e.hasStatic = True
            e.contactIdFull = 'auto'
            e.contactIdType = '3553'
            e.contactIdGroup = '00'
            e.contactIdZona = '00'
            e.objectId = MSObject.objectPCNId
            MSObject.eventsPGSM.append(e)
            MSObject.cameOOS = False
            MSObject.clearOffline = False
            doneNum += 1
        return doneNum
    
    def getEventsContactId(self, MSObject):
        timeRange   = self.getBeginEnd(MSObject.lastEvent_ContactId)
        events      = self.readURLData('contactId', MSObject.objectSKey, timeRange)
        return events

    def processEventsContactId(self, MSObject, Events):
        doneNum = 0
        if not Events:
            return
        for s in Events:
            try:
                e = MSData.MSEvent()
                e.fromContactId(self.parseEvent(s))
                e.objectId = MSObject.objectPCNId
                    #check e.eventGenerateTime < timeRange[0] (obj.last?) - error
                MSObject.eventsContactId.append(e)
                #MSObject.lastEvent_ContactId = e.eventReceiveTime
                if MSObject.lastEvent_ContactId and MSObject.lastEvent_ContactId < e.eventGenerateTime:
                    MSObject.lastEvent_ContactId = e.eventGenerateTime
                if not MSObject.lastEvent_ContactId:
                    MSObject.lastEvent_ContactId = e.eventGenerateTime
                if MSObject.lastEvent_PGSM and MSObject.lastEvent_PGSM < e.eventGenerateTime:
                        MSObject.lastEvent_PGSM = e.eventGenerateTime
                if not MSObject.lastEvent_PGSM:
                        MSObject.lastEvent_PGSM = e.eventGenerateTime
                MSObject.clearOffline = True
                doneNum += 1
            except Exception, err:
                MSLogger.logDebug('Worker::processEventsContactId: event(%s) error(%s)' % (str(s), str(err)))
                continue
        return doneNum
    
    def getEventsGPS(self, MSObject):
        timeRange   = self.getBeginEnd(MSObject.lastEvent_GPS)
        events      = self.readURLData('gpsPoints', MSObject.objectSKey, timeRange)
        return events

    def processEventsGPS(self, MSObject, Events):
        doneNum = 0
        if not Events:
            return
        for s in Events:
            try:
                e = MSData.MSEvent()
                e.fromGPSPoint(self.parseEvent(s))
                e.objectId = MSObject.objectPCNId
                    #check e.eventGenerateTime < timeRange[0] (obj.last?) - error
                MSObject.eventsGPS.append(e)
                MSObject.lastEvent_GPS = e.eventGenerateTime
                doneNum += 1
            except Exception, err:
                MSLogger.logDebug('Worker::processEventsGPS: event(%s) error(%s)' % (str(s), str(err)))
                continue
        return doneNum
 
